<?php 
use Wdl\validate\ValidateException;
use Wdl\validate\Validate; 
use Wdl\helper\webHelper;
 
defined('IN_IA') or exit('Access Denied');
global $_GPC, $_W;
load()->func('tpl'); 
$uniacid = webHelper::bindUniacid(); 
$openid = $_W['openid'];
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'home';	
if($operation == 'display'|| $operation=='fav'){
    $template_name = sprintf("slogs/display",  $operation);
}else{
    $template_name = sprintf("slogs/%s",  $operation);
}

 
$rd = !empty($_GPC['rd']) ? $_GPC['rd'] : 'index';	

$acttypes = [
    'display'=> 'view', 'fav'=> 'fav',
];
$acttype = $acttypes[ $operation ];

if($operation == 'home'){
    $stat['total'] = pdo_fetchcolumn("select count(*) as count from ".tablename('kbwdl_broker') ." where uniacid='$uniacid'");
    $stat['total_today'] = pdo_fetchcolumn("select count(*) as count from ".tablename('kbwdl_broker') ." where created_time>:created_time and uniacid='$uniacid'",['created_time'=> strtotime("-1 day")]);
    $stat['total_borker'] = pdo_fetchcolumn("select count(*) as count from ".tablename('kbwdl_broker') ." where iscompany>0 and uniacid='$uniacid'");
    $stat['total_visit'] = pdo_fetchcolumn("select sum(nums) as count from ".tablename('kbwdl_count') ." where stat_type=100 and uniacid='$uniacid'");
    $today = date('Ymd');
    //今日访问次数
    $stat['total_today_visit'] = pdo_fetchcolumn("select sum(nums) as count from ".tablename('kbwdl_count') ." where stat_type=100  and uniacid='$uniacid' and title='$today' ");

}elseif($operation=='display'|| $operation=='fav'){
   /*删除*/
    if(isset($_GPC['id']) && !empty($_GPC['id'])){
        pdo_delete('kbwdl_favorite', array('id'=>$_GPC['id'] , 'uniacid'=>$uniacid));
        /*删除成功*/
    }
    $pindex = max(1, intval($_GPC['page']));
    $psize = 15;
    $condition = ' WHERE a.`uniacid` = :uniacid  AND a.`acttype` = :acttype';
    $params = array('uniacid' => $uniacid,'acttype'=> $acttype);
    if (!empty($_GPC['keyword'])) {
            $condition .= '  AND ( a.`title` LIKE :title OR a.`smalltext` LIKE :title ) ';
            $params['title'] = '%' . trim($_GPC['keyword']) . '%';
    }
 
    $sql = 'SELECT COUNT(*) FROM ' . tablename('kbwdl_favorite')." as a " . $condition;
    $total = pdo_fetchcolumn($sql, $params);
    if (!empty($total)) {
            $sql = 'SELECT a.*,b.id as bid,b.nickname,b.avatar,b.mobile FROM ' . tablename('kbwdl_favorite')." as a left join ".
                    tablename("kbwdl_broker")." as b on a.openid=b.openid ". $condition . ' ORDER BY a.`id` DESC LIMIT ' . ($pindex - 1) * $psize . ',' . $psize;
            $list = pdo_fetchall($sql, $params);
            $pager = pagination($total, $pindex, $psize);
    }
    
    
    $ddacttype = ['feed'=>'预约','view'=>'浏览','newshopfav'=>'收藏','fav'=>'收藏',];
    $ddftype = ['22'=>'新房','23'=>'其他','8'=>'新房','3'=>'二手房',];
/**管理访客的消息 */
}elseif($operation == 'msg'){
    $pindex = max(1, intval($_GPC['page']));
    $psize = 15;
    $condition = " a.uniacid='$uniacid' ";
    $sql = 'SELECT COUNT(*) FROM ' . tablename('kbwdl_im_recent')." as a left join "
            .tablename('kbwdl_broker')." as b on a.acount = b.openid where " . $condition;
    $total = pdo_fetchcolumn($sql, $params);   
    $sql = 'SELECT a.*,b.id as bid,b.nickname,b.avatar,b.mobile,b.truename,b.iscompany FROM ' . tablename('kbwdl_im_recent')." as a left join "
            .tablename('kbwdl_broker')." as b on a.acount = b.openid where "
            . $condition . ' ORDER BY a.`addtime` DESC LIMIT ' . ($pindex - 1) * $psize . ',' . $psize;
    $list = pdo_fetchall($sql, $params);
    $pager = pagination($total, $pindex, $psize);
    if($list ){
        foreach($list as &$item){
            $item['from_acount_info'] = json_decode( $item['from_acount_info'],true);
            $content = "";
             //文本消息 
             if ($item['msgtype'] == 'TIMTextElem') {
                $temp = json_decode($item['lastmsg']);
                $content = $temp->Text;
            } else if ($item['msgtype'] == 'TIMImageElem') {
                //自定义消息  /
                $temp = json_decode($item['lastmsg']);
                
                $content = htmlspecialchars_decode('图片消息');
                
            } else {
                $temp = json_decode($item['lastmsg']);
                $content = htmlspecialchars_decode($temp->Text);
            }
            $item['content'] = $content;
            $item['from_thumb'] = tomedia($item['from_acount_info']['thumb']);
            $item['thumb'] =  tomedia($item['avatar'] );
            $item['nickname'] = !empty( $item['truename']) ?$item['truename']: $item['nickname'];
        }
        unset($item);
    }
    /**问答列表 */
}elseif($operation == 'replay'){
 
    if($rd == 'index'){
          /*删除*/
        if(isset($_GPC['id']) && !empty($_GPC['id'])){
            pdo_delete('kbwdl_replay', array('id'=>$_GPC['id'] , 'uniacid'=>$uniacid));
            /*删除成功*/
        } 
        $pindex = max(1, intval($_GPC['page']));
        $psize = 15;
        $condition = '  `uniacid` = :uniacid ';
        $params = array('uniacid' => $uniacid );
        if (!empty($_GPC['keyword'])) {
                $condition .= '  AND ( `titlepic` LIKE :title OR  `smalltext` LIKE :title ) ';
                $params['title'] = '%' . trim($_GPC['keyword']) . '%';
        }

        $sql = 'SELECT COUNT(*) FROM ' . tablename('kbwdl_replay')." WHERE " . $condition;
        $total = pdo_fetchcolumn($sql, $params);
        if (!empty($total)) {
                $sql = 'SELECT * FROM ' . tablename('kbwdl_replay')." WHERE ".  $condition . ' ORDER BY `id` DESC LIMIT ' . ($pindex - 1) * $psize . ',' . $psize;
                $list = pdo_fetchall($sql, $params);
                $pager = pagination($total, $pindex, $psize);
        }
       /**发布内容 */
    }elseif($rd == 'post'){
        if(isset($_GPC['id']) && !empty($_GPC['id'])){
            $id = $_GPC['id'] ;
            $item = pdo_fetch('select * from '.tablename('kbwdl_replay')." where id=:id and uniacid=:rid ", array('id'=>$_GPC['id'] , 'rid'=>$uniacid));
            /*编辑*/
        }  
        if(checksubmit()){
            try {
                Validate::make([
                    'titlepic' => 'required', 
                    'smalltext' => 'required', 
                ], [
                    'titlepic.required'   => '请输入问答标题', 
                    'smalltext.required'   => '请输入回复内容',
                ])->check( $_GPC['data'] );
            } catch (ValidateException $e) {  
                message( $e->getMessage());   
            }
            /*发布*/
            $save = $_GPC['data'];
            if($id){ 
                pdo_update('kbwdl_replay', $save,['id'=> $id,'uniacid'=> $uniacid]);
            }else{
                $save ['addtime'] =  TIMESTAMP;
                $save['uniacid'] = $uniacid;
                pdo_insert('kbwdl_replay', $save);
            }
           
            message("操作成功", $this->createWebUrl('slogs',['op'=>'replay'] ), 'success');
        }
      
    }
    $htype = ['99'=> '通用'];
    $ht = webHelper::house_type();
    foreach($ht as $h){
        $htype[ $h['zhutype'] ] = $h['name'];
    }

    
     
}elseif($operation =='msglist'){
        $id = $_GPC['id'];
        $sql = 'SELECT a.*,b.id as bid,b.nickname,b.avatar,b.mobile,b.truename,b.iscompany FROM ' . tablename('kbwdl_im_recent')." as a left join "
            .tablename('kbwdl_broker')." as b on a.acount = b.openid where a.id=:id ";
        $recent = pdo_fetch($sql, ['id'=> $id]);  

        $from = json_decode($recent['from_acount_info'], true);
      
        $fromAccount = $recent['from_acount'];
        $fromAccountPic =  tomedia($from['thumb']);
        $fromAccountName = $from['username'] ;

        $toAccount   = $recent['acount'];
        $toAccountPic   =  tomedia($recent['avatar']);
        $toAccountName =  !empty($recent['truename']) ? $recent['truename'] : $recent['nickname'];
        
        

        $config = array(
            'fromAccount'=>$fromAccount,
            'fromAccountPic'=> $fromAccountPic,
            'fromAccountName'=>$fromAccountName,
            'toAccount'=> $toAccount,
            'toAccountPic'=> $toAccountPic,
            'toAccountName'=> $toAccountName,
        );    
      
        $pageNum = 10;
        $page = max(1, $_GPC['page']);
        $pagesize = 10;
        $startlimit = ($page-1)* $pagesize;
        
        $condition  = " ( From_Account='$fromAccount' AND To_Account='$toAccount' ) OR  ( From_Account='$toAccount' AND To_Account='$fromAccount' ) ";
        if(empty($_GPC['total'])){
            $count = pdo_fetchcolumn(" SELECT COUNT(*) FROM  ".tablename("kbwdl_im_msg")." where $condition ");
            $totalpage = ceil($count / $pagesize);
        }else{
            $totalpage = $_GPC['total'];
        }
    
        /**/
        $sql =  "SELECT *  FROM ".tablename("kbwdl_im_msg")." where $condition order by id desc limit $startlimit, $pagesize";

        $data  = pdo_fetchall( $sql ); 
        krsort( $data, SORT_NUMERIC);
        $msglist = [];
        if(is_array($data))  {
            foreach ($data as $key => $item) {            
            
                $msglist[] = webHelper:: format_message($config, $item);
            
            }
        }
  
    include $this->template('slogs/msglist'); 
    exit;
}

$submenus = [    
    'home'=> ['name'=> '数据统计', 'do'=> 'slogs'],
    'msg'=> ['name'=> '访客消息', 'do'=> 'slogs'],
    'display'=> ['name'=> '浏览记录', 'do'=> 'slogs'],
    'fav'=> ['name'=> '收藏记录', 'do'=> 'slogs'],
    'replay'=> ['name'=> '问答设置', 'do'=> 'slogs'],
];

include $this->template('slogs/layout');